<!--
  -    Copyright (c) 2018-2025, lengleng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: lengleng (wangiegie@gmail.com)
  -->

<template>
  <div class="app-container calendar-list-container">
    <div class="title">个人中心</div>
    <div class="info">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        label-position="left">
        <div class="grid-content bg-purple">
          <el-form-item label="姓名：" prop="name">
            {{ userInfo.name || '-' }}
          </el-form-item>
          <el-form-item label="账号：" prop="username">
            {{ ruleForm.username || '-' }}
          </el-form-item>
          <el-form-item label="账号ID：" prop="userId">
            {{ ruleForm.userId || '-' }}
          </el-form-item>
          <el-form-item label="组织：" prop="username">
            {{ tenantData.name || '-' }}
          </el-form-item>
          <el-form-item label="角色：" prop="role">
            {{ ruleForm.roleName || '-' }}
          </el-form-item>
        </div>
      </el-form>
      <el-form class="form-btn">
        <el-form-item>
          <el-button type="add" size="small" @click="updateName">修改姓名</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="add" size="small" @click="updateNaPassword">修改密码</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog
      title="修改姓名"
      :visible.sync="dialogVisible"
      width="596px"
      :before-close="handleClose"
      custom-class="white-list-dialog">
      <el-form
        ref="updateName"
        :model="addFormData"
        :rules="rules"
        width="596px"
        label-width="100px"
        label-position="right">
        <el-form-item label="新姓名" prop="name">
          <el-input v-model="addFormData.name" placeholder="请输入姓名" maxlength="20" clearable></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="14" @click="handleClose">取消</el-button>
        <el-button type="primary" size="14" @click="onsubmitName">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改密码"
      :visible.sync="dialogPassVisible"
      width="596px"
      :before-close="handlePassClose"
      custom-class="white-list-dialog">
      <el-form
        ref="updatePassword"
        :model="addPassFormData"
        :rules="rulesPass"
        width="596px"
        label-width="100px"
        label-position="right">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="addPassFormData.oldPassword" :type="oldPasswordType" placeholder="请输入旧密码" maxlength="20">
            <i slot="suffix" class="el-icon-view el-input__icon" @click="showOldPassword" />
          </el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="addPassFormData.password" :type="passwordType" placeholder="请输入新密码" maxlength="20">
            <i slot="suffix" class="el-icon-view el-input__icon" @click="showPassword" />
          </el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="addPassFormData.confirmPassword" :type="confirmPasswordType" placeholder="请再次输入新密码" maxlength="20">
            <i slot="suffix" class="el-icon-view el-input__icon" @click="showConfirmPassword" />
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="14" @click="handlePassClose">取消</el-button>
        <el-button type="primary" size="14" @click="onsubmitPassword">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { handleImg, openWindow } from '@/util'
import { mapState, mapGetters } from 'vuex'
import store from '@/store'
import { getStore } from '@/util/store'
import { editInfo, infoModifyPassword } from '@/api/admin/user'
import { Base64 } from 'js-base64'

export default {
  data() {
    return {
      avatarUrl: '',
      headers: {
        'TENANT-ID': store.getters.userInfo.tenantId,
        Authorization: 'Bearer ' + store.getters.access_token
      },
      ruleForm: {
        username: '',
        password: '',
        newpassword1: '',
        newpassword2: '',
        avatar: '',
        phone: '',
        nickname: '',
        name: '',
        email: '',
        roleName: '',
        tenantName: '',
        userId: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 1, max: 20, message: '请输入姓名', trigger: 'blur' },
          { validator: this.validateName, trigger: 'blur' }
        ]
      },
      rulesPass: {
        oldPassword: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 8, max: 64, message: '请输入规范的密码', trigger: 'blur' },
          { validator: this.validatePassword, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 8, max: 64, message: '请输入规范的密码', trigger: 'blur' },
          { validator: this.validatePassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入输入登录密码', trigger: 'blur' },
          { min: 8, max: 64, message: '请输入规范的密码', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ]
      },
      dialogVisible: false,
      dialogPassVisible: false,
      addFormData: {
        name: ''
      },
      addPassFormData: {
        oldPassword: '',
        password: '',
        confirmPassword: ''
      },
      oldPasswordType: 'password',
      passwordType: 'password',
      confirmPasswordType: 'password'
    }
  },
  computed: {
    ...mapGetters(['roleData', 'tenantData']),
    ...mapState({
      userInfo: (state) => state.user.userInfo
    })
  },
  created() {
    this.resetForm()
  },
  methods: {
    // 密码校验
    validatePassword(rule, value, callback) {
      // if (this.addPassFormData.confirmPassword !== '' && value !== this.addPassFormData.confirmPassword) {
      //   callback(new Error("两次输入的密码不一致"))
      // } else {
      //   callback()
      // }
      const flag = new RegExp(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z0-9!@#$%^&*()\-_=+[\]{}|\\:;"'<>,.?/~`]+$/).test(value)
      if (!flag) {
        callback(new Error('请输入规范的密码'))
      } else {
        callback()
      }
    },
    // 确认密码校验
    validateConfirmPassword(rule, value, callback) {
      if (value === this.addPassFormData.password) {
        callback()
      } else {
        callback(new Error("两次输入的密码不一致"))
      }
      const flag = new RegExp(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z0-9!@#$%^&*()\-_=+[\]{}|\\:;"'<>,.?/~`]+$/).test(value)
      if (!flag) {
        callback(new Error('请输入规范的密码'))
      } else {
        callback()
      }
    },
    // 姓名
    validateName(rule, value, callback) {
      if (value.trim() === '') {
        callback(new Error('请输入姓名'))
      } else {
        callback()
      }
    },
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          return false
        }
        editInfo(this.ruleForm).then((response) => {
          this.$notify.success('修改成功')
          // 修改后注销当前token,重新登录
          this.$store.dispatch('LogOut').then(() => {
            location.reload()
          })
        })
      })
    },
    resetForm() {
      this.ruleForm.password = undefined
      this.ruleForm.newpassword1 = undefined
      this.ruleForm.newpassword2 = undefined
      this.ruleForm.username = this.userInfo.username
      this.ruleForm.phone = this.userInfo.phone
      this.ruleForm.avatar = this.userInfo.avatar
      this.ruleForm.nickname = this.userInfo.nickname
      this.ruleForm.name = this.userInfo.name
      this.ruleForm.email = this.userInfo.email
      this.ruleForm.userId = this.userInfo.userId
      this.ruleForm.roleName = this.roleData.roleName
      this.ruleForm.tenantName = this.tenantData.name
      handleImg(this.userInfo.avatar, 'avatar')
      //判断是否选择了租户ID
      const TENANT_ID = getStore({ name: 'tenantId' })
      if (TENANT_ID) {
        this.headers['TENANT-ID'] = TENANT_ID // 租户ID
      }
    },
    handleAvatarSuccess(res, file) {
      this.avatarUrl = URL.createObjectURL(file.raw)
      this.ruleForm.avatar = res.data.url
    },
    handleClick(thirdpart) {
      let appid, client_id, url
      const redirect_uri = encodeURIComponent(
        window.location.origin + '/#/authredirect'
      )
      if (thirdpart === 'wechat') {
        appid = 'wxd1678d3f83b1d83a'
        url = `https://open.weixin.qq.com/connect/qrconnect?appid=${appid}&redirect_uri=${redirect_uri}&state=WX-BIND&response_type=code&scope=snsapi_login#wechat_redirect`
      } else if (thirdpart === 'tencent') {
        client_id = '101322838'
        url = `https://graph.qq.com/oauth2.0/authorize?response_type=code&state=QQ-BIND&client_id=${client_id}&redirect_uri=${redirect_uri}`
      } else if (thirdpart === 'gitee') {
        client_id =
          'f5a05b92e869e4e3e037dffc3d54b2bb7fb9d5e45bcde67cd6472adb03e0b9dd'
        url = `https://gitee.com/oauth/authorize?response_type=code&state=GITEE-BIND&client_id=${client_id}&redirect_uri=${redirect_uri}`
      } else if (thirdpart === 'osc') {
        client_id = 'neIIqlwGsjsfsA6uxNqD'
        url = `https://www.oschina.net/action/oauth2/authorize?response_type=code&client_id=${client_id}&state=OSC-BIND&redirect_uri=${redirect_uri}`
      }
      openWindow(url, thirdpart, 540, 540)
    },
    // 修改姓名
    updateName() {
      this.dialogVisible = true
    },
    // 关闭修改姓名弹窗
    handleClose() {
      this.dialogVisible = false
      this.$refs['updateName'].resetFields()
    },
    // 修改密码
    updateNaPassword() {
      this.dialogPassVisible = true
    },
    // 关闭修改密码弹窗
    handlePassClose() {
      this.dialogPassVisible = false
      this.$refs['updatePassword'].resetFields()
    },
    showOldPassword() {
      this.oldPasswordType === ''
        ? (this.oldPasswordType = 'password')
        : (this.oldPasswordType = '')
    },
    showPassword() {
      this.passwordType === ''
        ? (this.passwordType = 'password')
        : (this.passwordType = '')
    },
    showConfirmPassword() {
      this.confirmPasswordType === ''
        ? (this.confirmPasswordType = 'password')
        : (this.confirmPasswordType = '')
    },
    onsubmitName() {
      this.$refs.updateName.validate(valid => {
        if (valid) {
          const params = {
            ...this.addFormData,
            name: this.addFormData.name.trim(),
            userId: this.ruleForm.userId
          }
          infoModifyPassword(params).then(res => {
            this.$store.dispatch('GetUserInfo')
            this.$nextTick(() => {
              this.resetForm()
            })
            this.$message.success('修改成功!')
          }).catch(err => {
            this.$message.error(err.message)
          }).finally(() => {
            this.dialogVisible = false
            this.$refs['updateName'].resetFields()
          })
        } else {
          return false
        }
      })
    },
    onsubmitPassword() {
      this.$refs.updatePassword.validate(valid => {
        if (valid) {
          const params = {
            oldPassword: Base64.encode(this.addPassFormData.oldPassword),
            password: Base64.encode(this.addPassFormData.password),
            userId: this.ruleForm.userId
          }
          infoModifyPassword(params).then(res => {
            this.$store.dispatch('GetUserInfo')
            this.$nextTick(() => {
              this.resetForm()
            })
            this.$message.success('修改成功!')
          }).catch(err => {
            this.$message.error(err.message)
          }).finally(() => {
            this.dialogPassVisible = false
            this.$refs['updatePassword'].resetFields()
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.title {
  font-weight: 600;
  color: #252525;
}

.info {
  margin-top: 16%;
  margin-left: 35%;
  display: flex;

  ::v-deep .el-form .grid-content .el-form-item__label {
    color: #808080;
  }
  ::v-deep .el-form .grid-content .el-form-item__content {
    color: #252525;
  }

  .form-btn {
    margin-left: 58px;
  }
}

.demo-ruleForm .el-form-item__label {
  font-weight: 400;
  color: #808080;
}

.demo-ruleForm .el-form-item__content {
  font-weight: 400;
  color: #252525;
}
</style>
<style lang="scss">
@import "@/styles/info.scss";
</style>
